<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" width="68px">
      <el-form-item label="所属方案" prop="schemeId">
        <el-select v-model="queryParams.schemeId" filterable placeholder="请输入所属方案" clearable size="small" style="width: 160px">
          <el-option
            v-for="scheme in schemeIdOptions"
            :key="scheme.schemeId"
            :label="scheme.schemeName"
            :value="scheme.schemeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作业名称" prop="workName">
        <el-input
          v-model="queryParams.workName"
          placeholder="请输入作业名称"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="集成表" prop="tableName">
        <el-select v-model="queryParams.tableName" filterable placeholder="请输入集成表" clearable size="small"
                   style="width: 160px">
          <el-option
            v-for="table in tableNameOptions"
            :key="table.busTableName"
            :label="table.busTableComment"
            :value="table.busTableName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="作业类型" prop="workType">
        <el-select v-model="queryParams.workType" placeholder="请选择作业类型" clearable size="small" style="width: 160px">
          <el-option
            v-for="dict in workTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择使用状态" clearable size="small" style="width: 160px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['datafactory:work:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['datafactory:work:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['datafactory:work:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(true)"
          v-hasPermi="['datafactory:work:edit']"
        >启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-video-pause"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(false)"
          v-hasPermi="['datafactory:work:edit']"
        >禁用
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--		  plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['app:work:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table border ref="fileTable" v-loading="loading" :data="workList" @selection-change="handleSelectionChange"
              :row-class-name="tabRowClassName" @row-click="selectThisRow">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="编号" align="center" prop="workId" />-->
      <el-table-column label="作业名称" align="center" prop="workName" :show-overflow-tooltip="true"/>
      <el-table-column label="所属方案" align="center" prop="schemeId" :formatter="schemeIdFormat"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="集成表" align="center" prop="tableName" :formatter="tableNameFormat"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="作业类型" align="center" prop="workType" :formatter="workTypeFormat"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="优先级" align="center" prop="workOrder"/>
      <el-table-column label="使用状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="作业说明" align="center" prop="workExplain" show-overflow-tooltip="true" v-if="condition"/>
      <el-table-column label="创建人姓名" align="center" prop="creatorName"/>
      <el-table-column label="创建日期" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datafactory:work:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datafactory:work:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改作业对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="作业名称" prop="workName">
              <el-input v-model="form.workName" placeholder="请输入作业名称" style="width: 90%"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属方案" prop="schemeId">
              <el-select v-model="form.schemeId" filterable placeholder="请输入所属方案" @change="queryWorkOrder">
                <el-option
                  v-for="scheme in schemeIdOptions"
                  :key="scheme.schemeId"
                  :label="scheme.schemeName"
                  :value="scheme.schemeId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item v-if="typeVal != 6" label="集成表" prop="this.tableName">
              <el-select v-model="form.tableName" filterable placeholder="请输入业务表">
                <el-option
                  v-for="table in tableNameOptions"
                  :key="table.busTableName"
                  :label="table.busTableComment"
                  :value="table.busTableName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="作业类型" prop="workType">
              <el-select v-model="form.workType" placeholder="请选择作业类型" @change="showOrHide">
                <el-option
                  v-for="dict in workTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item v-if="isAdd === false" label="优先级" v-model="form.workOrder" prop="workOrder">
              <el-input-number :min="1" v-model="form.workOrder"></el-input-number>
            </el-form-item>
          </el-col>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item v-if="isAdd" label="优先级 " v-model="form.workOrder" prop="workOrder">
                {{form.workOrder}}
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item v-if="typeVal == 5" label="ELT作业 " v-model="form.etlJobId" prop="etlJobId">
                <el-select v-model="form.etlJobId">
                  <el-option
                    v-for="job in jobListOptions"
                    :key="job.id"
                    :label="job.jobName"
                    :value="parseInt(job.id)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item v-if="typeVal == 3" label="ETL转换 " v-model="form.etlTransId" prop="etlTransId">
                <el-select v-model="form.etlTransId">
                  <el-option
                    v-for="trans in transListOptions"
                    :key="trans.id"
                    :label="trans.transName"
                    :value="parseInt(trans.id)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
          <el-form-item v-if="isAdd === false" label="使用状态">
            <el-select v-model="form.status">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>
        <el-form-item label="作业脚本" prop="workScript">
          <el-input v-model="form.workScript" type="textarea" placeholder="请输入内容" style="width: 80%"/>
        </el-form-item>
        <el-form-item label="作业说明" prop="workExplain">
          <el-input v-model="form.workExplain" type="textarea" placeholder="请输入作业说明" style="width: 80%"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listWork,
    getWork,
    delWork,
    addWork,
    updateWork,
    getWorkOrder,
    getPriority,
    updateUseStatus
  } from "@/api/datafactory/work";
  import {getSchemes} from "@/api/datafactory/scheme";
  import {getTables} from "@/api/datafactory/table";
  import {getTransList} from "@/api/kettle/trans";
  import {getJobList} from "@/api/kettle/job";

  export default {
    name: "Work",
    components: {},
    data() {
      return {
        typeVal:0,
        //隐藏作业说明
        condition: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 是否是启动或禁用
        isStart: false,
        // 初始优先级
        initPriority: 0,
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 作业表格数据
        workList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 判断当前窗口是新增还是修改
        isAdd: false,
        // 作业类型字典
        workTypeOptions: [],
        // 数据状态字典
        statusOptions: [],
        // ETL作业
        jobListOptions: [],
        // ETL转换
        transListOptions: [],
        // 业务表名称
        tableNameOptions: [],
        // 所属方案
        schemeIdOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          schemeId: null,
          workName: null,
          tableName: null,
          workType: null,
          status: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          schemeId: [
            {required: true, message: "所属方案不能为空", trigger: "blur"}
          ],
          workName: [
            {required: true, message: "作业名称不能为空", trigger: "blur"}
          ],
          tableName: [
            {required: true, message: "业务表不能为空", trigger: "blur"}
          ],
          workType: [
            {required: true, message: "作业类型不能为空", trigger: "change"}
          ],
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("work_type").then(response => {
        this.workTypeOptions = response.data;
      });
      this.getDicts("data_level").then(response => {
        this.statusOptions = response.data;
      });
      var table = {"tableStatus": 1};
      getTables(table).then(response => {
        this.tableNameOptions = response;
      });
      var scheme = {"status": 1}
      getSchemes(scheme).then(response => {
        this.schemeIdOptions = response;
      });
      var trans = {"delFlag": 0}
      getTransList(trans).then(response => {
        this.transListOptions = response;
      });
      var job = {"delFlag":0}
      getJobList(job).then(response => {
        this.jobListOptions = response;
      });
      this.tableHeight = (document.body.offsetHeight)-270
    },
    methods: {
      /** 更改斑马纹 */
      tabRowClassName({row,rowIndex}){
        let index = rowIndex + 1;
        if(index %2 == 0){
          return 'two-color'
        }else {
          return "one-color"
        }
      },
      selectThisRow(row){
        this.$refs.fileTable.toggleRowSelection(row);
      },
      /** 查询作业列表 */
      getList() {
        this.loading = true;
        listWork(this.queryParams).then(response => {
          this.workList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      showOrHide(val){
        this.typeVal = val;
      },
      // 作业类型字典翻译
      workTypeFormat(row, column) {
        return this.selectDictLabel(this.workTypeOptions, row.workType);
      },
      // 数据状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      schemeIdFormat(row, column) {
        var schemeId = row.schemeId;
        var schemeName = "";
        this.schemeIdOptions.forEach(item => {
          if (item.schemeId == schemeId) {
            schemeName = item.schemeName;
          }
        });
        return schemeName
      },
      tableNameFormat(row, column) {
        var tableComment = "";
        this.tableNameOptions.forEach(item => {
          if (item.busTableName == row.tableName) {
            tableComment = item.busTableComment;
          }
        });
        return tableComment
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          workId: null,
          schemeId: null,
          workName: null,
          tableName: null,
          workExplain: null,
          workType: null,
          workScript: null,
          workOrder: null,
          workOderS: null,
          status: 0,
          creatorName: null,
          createDate: null,
          etlJobId:null,
          etlTransId:null
        };
        // this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.workId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.isAdd = true;
        this.typeVal= 0;
        this.title = "添加作业";
      },
      //查询作业优先级列表
      queryWorkOrder() {
        if (this.isAdd && this.form.schemeId != null) {
          getWorkOrder(this.form.schemeId).then(response => {
            this.form.workOrder = response.data;
          });
        } else if (this.isAdd === false) {
          getPriority(this.form.schemeId).then(response => {
            this.form.workOderS = response.data;
          });
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        if (row.workType==3||5){
          this.typeVal = row.workType;
        }
        this.isAdd = false;
        const workId = row.workId || this.ids
        getWork(workId).then(response => {
          this.form = response.data;
          this.initPriority = this.form.workOrder;
          this.open = true;
          this.title = "修改作业";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.workId != null) {
              // 优先级校验
              for (let i = 0; i < this.form.workOderS.length; i++) {
                if (this.initPriority != this.form.workOrder) {
                  if (this.form.workOrder > this.form.workOderS[0]) {
                    return this.msgError("不能超过当前优先域");
                  }
                }
              }
              updateWork(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addWork(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const workIds = row.workId || this.ids;
        this.$confirm('是否确认删除作业编号为"' + workIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delWork(workIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 使用或禁用状态更新 */
      handleStatus(isStart) {
        this.isStart = isStart;
        let statusNo = 0;
        if (isStart === true) {
          var status = '启动';
          statusNo = 1;
        } else {
          status = '禁用';
          statusNo = 2;
        }
        const workIds = this.ids;
        this.$confirm('是否' + status + '"' + workIds + '"的数据项?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
            return updateUseStatus(workIds, statusNo);
        }).then(() => {
          this.getList();
          this.msgSuccess(status + '成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('datafactory/work/export', {
          ...this.queryParams
        }, `datafactory_work.xlsx`)
      }
    }
  };
</script>
